#include <iostream>
#include <cstdlib>
#include <string>
#include <algorithm>
#include "TcpServer.hpp"

void Usage(const std::string &proc)
{
    std::cout << "Usage:\n\t" << proc << "  serveroprt" << std::endl;
}

void Interact(int sockfd, std::string &out, std::string in)
{
    char buffer[1024];
    int n = read(sockfd, buffer, sizeof(buffer) - 1);
    if (n > 0)
    {
        buffer[n] = 0;
        write(sockfd, in.c_str(), in.size());
    }
    else if (n == 0) 
    {
        lg.LogMessage(Info, "client quit...\n");
    }
    else
    {
        lg.LogMessage(Error, "read socket error, errno code: %d, error string: %s\n", errno, strerror(errno));
    }
}

void Ping(int sockfd, InetAddr &addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd : %d\n", addr.DebugPrint().c_str(), "ping", sockfd);
    std::string message;
    Interact(sockfd, message, "Pong");
}

void Translation(int sockfd, InetAddr &addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd : %d\n", addr.DebugPrint().c_str(), "translation", sockfd);
    std::string ans;
    ans += "selece server: Translation success!!!";
    write(sockfd, ans.c_str(), ans.size());
}

void Conversion(int sockfd, InetAddr &addr)
{
    lg.LogMessage(Debug, "%s select %s success, fd : %d\n", addr.DebugPrint().c_str(), "conversion", sockfd);
    char message[128];
    int n = read(sockfd, message, sizeof(message) - 1);
    if(n > 0)
        message[n] = 0;
    std::string messagebuf = message;
    std::transform(messagebuf.begin(), messagebuf.end(), messagebuf.begin(),[](unsigned char c){
        return std::toupper(c);
    });
    write(sockfd, messagebuf.c_str(), messagebuf.size());
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(-1);
    }

    uint16_t serverport = std::stoi(argv[1]);
    TcpServer tsvr(serverport);
    tsvr.RegisterFunc("ping", Ping);
    tsvr.RegisterFunc("translation", Translation);
    tsvr.RegisterFunc("conversion", Conversion);
    tsvr.Init();
    tsvr.Start();

    return 0;
}
